import { Injectable, BadRequestException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { v4 as uuidv4 } from 'uuid';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}
  async login(
    username: string,
  ): Promise<{ token: string } | { message: string }> {
    const user = await this.usersRepository.findOne({ where: { username } });
    if (!user) {
      throw new BadRequestException('用户名不存在，请先注册', {
        cause: new Error(),
        description: '用户名不存在，请先注册',
      });
    }
    if (!user.isActive) {
      throw new BadRequestException('账号未激活，请联系管理员', {
        cause: new Error(),
        description: '账号未激活，请联系管理员',
      });
    }
    const token = uuidv4();
    return { token, ...user };
  }

  async register(
    username: string,
    password: string,
  ): Promise<{ message: string; success?: boolean }> {
    const existingUser = await this.usersRepository.findOne({
      where: { username },
    });
    if (existingUser) {
      throw new BadRequestException('用户名已存在，请更换用户名', {
        cause: new Error(),
        description: '用户名已存在，请更换用户名',
      });
    }
    const newUser = this.usersRepository.create({
      username,
      password,
    });
    await this.usersRepository.save(newUser);
    return { message: '注册成功', success: true };
  }
}
